<?php

/**
 * Created by PhpStorm.
 * Author: 赵凯
 * Date: 2020/1/6
 * Time: 18:06
 */
namespace api\message\controller;

use api\common\service\CurlService;
use think\Controller;

class PushMessageController extends Controller
{
    /**
     * 发送模板消息
     * $openid  用户openid
     * $message  发送的消息 array
     */
    public function send($openid,$page,$message)
    {
        $data = [
            'openid' => $openid,
            'page' => $page,
//            'form_id' => '',//模板消息需要的formid
            'data' =>$message
        ];

        $ret = $this->templateMessage($data);
        if($ret)
        {
            return $ret;
        }else{
            return 'faile';
        }

    }

    /**
     * @param $params [参数]
     * @param $appid [小程序appid]
     * @param $secret [小程序secret]
     * @param $type [模板消息的类型] 如：审核，通知， 签到 。。。。
     */
    public function templateMessage($params)
    {
        $appid=\think\Config::get('***********');
        $secret=\think\Config::get('**********');
        # 模板关键字
        $data = [];
        foreach ($params['data'] as $k => $v) {
            $data['thing'.($k+1)] = ['value'=>$v];
        }
        $postData = [
            'touser'        =>  $params['openid'],
            'template_id'   =>  '',//这是模板id,需要去申请
            'page'          =>  $params['page'],
//            'form_id'       =>  $params['form_id'],
            'data'          =>  $data
        ];

        # user_token 必须全局获取|存储
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $result =CurlService::curlRequest($url,[]);
        $access_token = $result['access_token'];
//        $urls = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
        $urls = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
        $postData = json_encode($postData);
        $ret =CurlService::curlRequest($urls, $postData,'POST');
        return $ret;
    }

}